import os
from django.http import HttpResponseRedirect
from django.shortcuts import render,redirect
from loguru import logger
from .models import Website, Rad
from apps.staruser.models import LoginHistory,StarUser
from ..prescription.models import Prescription
from apps.cus_service.models import Cus_Contact
from rest_framework.decorators import api_view
from datetime import datetime
from apps.TabletInfo.models import TabletInfo
from .handler import getSex


# Create your views here.

def welcome(request):
    context = {}
    return render(request, 'welcome.html', context)

def service(request):
    website_obj = Website.objects.filter(is_delete=False, is_active=True)

    if not website_obj:
        logger.debug("未维护网站信息请检查是否已删除或禁用")
        return HttpResponseRedirect('/login')

    context = {}
    cus_contact = Cus_Contact.objects.filter(is_delete=False,is_active=True)
    context["contact_list"] = cus_contact
    context["comp_address"] = website_obj[0].address if website_obj[0].address else ""
    return render(request, 'service.html', context)


def index(request):
    user_id = request.session.get("userid", None)
    if not user_id:
        return HttpResponseRedirect('/login')
    else:
        loginhistory = LoginHistory.objects.filter(user__id=user_id,loginstatus=True).order_by("-id")
        if loginhistory:
            login_obj = loginhistory[0]
            log_num = login_obj.username if login_obj else ""
            loginnum = login_obj.loginnum if login_obj.loginnum else ""
            LoginHistory.objects.filter(user_id=user_id,loginstatus=True).exclude(pk=login_obj.pk).update(loginstatus=False)
        else:
            return HttpResponseRedirect('/login')

    website_obj = Website.objects.filter(is_delete=False,is_active=True)

    if not website_obj:
        logger.debug("未维护网站信息请检查是否已删除或禁用")
        return HttpResponseRedirect('/login')

    context = {
        'title': website_obj[0].name,
        'btn_1': website_obj[0].btn_1,
        'btn_2': website_obj[0].btn_2,
        'btn_3': website_obj[0].btn_3,
        'apiurl': website_obj[0].apiurl,
        'title':website_obj[0].name,
        'login_id':id,
        'loginnum':loginnum,
        'log_num':log_num
    }

    return render(request, 'index.html', context)

def buy_med(request):
    context = {

    }
    return render(request,'userinfo.html',context)

def peisong(request):
    context = {}
    return render(request, 'peisong.html', context)



def self_prescrip(request):
    context = {}
    return render(request, 'self_prescrip.html', context)


def rad(request):
    context = {}
    return render(request, 'Rad/new_order.html', context)

@api_view(["GET"])
def Order(request):
    type = request.query_params.get('type', None)
    user_id = request.session.get("userid", None)
    if not user_id:
        return HttpResponseRedirect('/user/login')
    rad = Rad.objects.filter(is_delete=False,is_active=True)

    type = request.query_params.get('type', None)
    context = {}
    if type=="self":
        context["self"]=True
        # 当前登录用户
        user_id = request.session.get("userid", None)
        if not user_id:
            return HttpResponseRedirect('/user/login')
        current_date = datetime.now().strftime("%Y-%m-%d")
        # 新增自编方数据表
        prescription = Prescription.objects.filter(is_delete=False,
                                                   is_active=True,
                                                   OrderStatus="0",
                                                   OrderType="0",
                                                   user__id=user_id,
                                                   OrderDt=current_date)
        if prescription:
            prescription_obj = prescription[0]
        else:
            # 将以前的未完成的处理掉，不在选择时显示
            Prescription.objects.filter(is_delete=False,
                                        is_active=True,
                                        OrderStatus="0",
                                        OrderType="0",
                                        user__id=user_id,
                                        ).exclude(OrderDt=current_date).update(is_active=False)
            staruser_obj = StarUser.objects.filter(pk=user_id)[0]
            prescription_obj = Prescription.objects.create(OrderDt=datetime.now(),
                                                           OrderNum=datetime.now().strftime("%Y%m%d%H%M%S"),
                                                           OrderDtm=datetime.now(),
                                                           OrderType="0",
                                                           user=staruser_obj)
        tablet_info = TabletInfo.objects.all()
        context["OrderDt"] = prescription_obj.OrderDt.strftime("%Y-%m-%d")
        context["OrderNum"] = prescription_obj.OrderNum
        context["prescription_id"] = prescription_obj.pk
        context["tablet_info_list"] = tablet_info
        return render(request, 'Order/selfprescription.html', context)
    else:
        # 自编方 0
        prescription_0 = Prescription.objects.filter(is_delete=False, is_active=True, OrderStatus="0",OrderType="0", user__id=user_id)
        # 专业方 1
        prescription_1 = Prescription.objects.filter(is_delete=False, is_active=True, OrderStatus="0",OrderType="1", user__id=user_id)

        context = {
            "prescription_0_list": prescription_0,
            "prescription_0_length":prescription_0.count(),
            "prescription_1_list": prescription_1,
            "prescription_1_length": prescription_1.count(),
            "user_id": user_id,
            "rad_list": rad
        }
        return render(request, 'Order/new_order.html', context)


def userinfo(request):
    user_id = request.session.get("userid", None)
    if not user_id:
        return HttpResponseRedirect('/user/login')

    startuser_list = StarUser.objects.filter(is_delete=False,pk=user_id)
    if startuser_list:
        startuser_obj = startuser_list[0]
    else:
        return HttpResponseRedirect('/login')

    sex_value = startuser_obj.sex if startuser_obj.sex else ""
    Male_checked=getSex('男',sex_value)
    Fmale_checked=getSex('女',sex_value)

    context = {
        "user_id": user_id,
        "user_name": startuser_obj.username,
        "full_name": startuser_obj.fullname,
        "is_active": "checked" if startuser_obj.is_active else "",
        "sex_male":Male_checked,
        "sex_fmale":Fmale_checked,
        "email":startuser_obj.email if startuser_obj.email else "",
        "mobile": startuser_obj.mobile if startuser_obj.mobile else "",
        "address": startuser_obj.address if startuser_obj.address else "",
        "modifypwd":startuser_obj.modfitypwd if startuser_obj.modfitypwd else "0"
    }
    return render(request, os.path.join('user','userinfo.html'),context)


def changepwd(request):
    user_id = request.session.get("userid", None)
    if not user_id:
        return HttpResponseRedirect('/user/login')
    context = {
        "user_id": user_id
    }
    return render(request, os.path.join('user','changepwd.html'),context)
